package com.rr.middle;

/**
 * @author zhuangcanrun
 * @Date 2022/05/30/18:50
 * @description
 **/

/*
 * https://leetcode.cn/problems/validate-ip-address/
 * */
public class ValidIPAddress {

    public String validIPAddress(String queryIP) {
        if (queryIP == null || queryIP.length() == 0 || queryIP.startsWith(".") || queryIP.endsWith(".") || queryIP.startsWith(":") || queryIP.endsWith(":")) {
            return "Neither";
        }
        String[] split = null;
        split = queryIP.split("\\.");
        if (split.length == 4) {
            return isIpv4(split) ? "IPv4" : "Neither";
        }
        split = queryIP.split(":");
        if (split.length == 8) {
            return isIpv6(split) ? "IPv6" : "Neither";
        }
        return "Neither";
    }

    private boolean isIpv6(String[] split) {
        for (String s : split) {
            if (s.length() == 0 || s.length() > 4) {
                return false;
            }
            Boolean bigLetter = null;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c >= '0' && c <= '9') {
                    continue;
                }else if (bigLetter == null && c >= 'a' && c <= 'f') {
                    bigLetter = false;
                    continue;
                }else if (bigLetter == null && c >= 'A' && c <= 'F') {
                    bigLetter = true;
                    continue;
                }else if (bigLetter != null && bigLetter && c >= 'a' && c <= 'f'){
                    return false;
                }else if (bigLetter != null && !bigLetter && c >= 'A' && c <= 'F'){
                    return false;
                }
            }
        }
        return true;
    }

    private boolean isIpv4(String[] split) {
        for (String item : split) {
            try {
                int i = Integer.parseInt(item);
                if (!((i > 0 && i <= 255) || (i == 0 && item.length() == 1)) || (i > 0 && item.charAt(0) == '0')) {
                    return false;
                }
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(new ValidIPAddress().validIPAddress("2001:db8:85a3:0::8a2E:0370:7334"));
    }

}
